﻿using MessagePack;
using Service.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Service.Utity
{
    public static class ConfigHelper
    {
        public static void SaveConfig(this AutomaticConfig automaticConfig,RSA rsa, string filePath)
        {
            //对数据加密
            foreach (var item in automaticConfig.DnsEditorConfig.ConfigItems)
            {
                if (item.IsSecret)
                {
                    automaticConfig.DnsEditorConfig.Config[item.Key] = automaticConfig.DnsEditorConfig.Config[item.Key].Encrypt(rsa);
                }
            }
            foreach (var cConfig in automaticConfig.CertHandOutConfig)
            {
                foreach (var item in cConfig.ConfigItems)
                {
                    if (item.IsSecret)
                    {
                        cConfig.Config[item.Key] = cConfig.Config[item.Key].Encrypt(rsa);
                    }
                }
            }
            //对类执行序列化，保存到文件..
            byte[] serialized = MessagePackSerializer.Serialize(automaticConfig);
            File.WriteAllBytes(filePath, serialized);
        }
        public static AutomaticConfig GetConfig(RSA rsa, string filePath)
        {
            var sourceBytes = File.ReadAllBytes(filePath);
            var automaticConfig = MessagePackSerializer.Deserialize<AutomaticConfig>(sourceBytes);
            //解密拿到原始数据
            foreach (var item in automaticConfig.DnsEditorConfig.ConfigItems)
            {
                if (item.IsSecret)
                {
                    automaticConfig.DnsEditorConfig.Config[item.Key] = automaticConfig.DnsEditorConfig.Config[item.Key].Decrypt(rsa);
                }
            }
            foreach (var cConfig in automaticConfig.CertHandOutConfig)
            {
                foreach (var item in cConfig.ConfigItems)
                {
                    if (item.IsSecret)
                    {
                        cConfig.Config[item.Key] = cConfig.Config[item.Key].Decrypt(rsa);
                    }
                }
            }
            return automaticConfig;
        }
    }
}
